import React, { useState, memo, useEffect } from 'react';
import { Table, Button, Row, Col, Form, Select, Input, Radio, message } from 'tdesign-react';
import { getListApi, createFormApi } from 'api/operation/channel';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import SakuraModal from 'components/SakuraModal';
import { createColumns } from 'utils/tableUtils';
import { CHANNEL_PROMOTION_MAP, ENABLE_MAP, PROMOTION_MAP, OPT_ERROR_MSG } from 'constants/index';
import SakuraSearchForm from 'components/SakuraSearchForm';

import IppeakTable from 'components/IppeakTable';
import { set } from 'lodash';

export interface FormField {
  label: string;
  name: string;
  type: 'select' | 'input' | 'radio';
  required?: boolean;
  options?: {
    label: string;
    value: number | string;
  }[];
}
// 渠道推广Layout

export const SelectTable: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const initData = {
    platform: '论坛',
    status: 1,
  };
  const { loading, setLoading } = useLoading(false);

  const columns = createColumns([
    {
      label: '推广平台',
      key: 'promotion_platform',
      width: '200',
    },
    {
      label: '渠道名称',
      key: 'name',
      width: '140',
      textBreak: true,
    },
    {
      label: '渠道推广页面',
      key: 'promotion_domain',
      width: '250',
    },
    {
      label: '渠道推广链接',
      key: 'promotion_link',
      width: '300',
    },
    {
      label: '状态',
      key: 'status',
      enumConf: {
        options: ENABLE_MAP,
        type: 'Array',
      },
    },
    {
      label: 'UV',
      key: 'exclusive_visits_num',
      sorter: true,
    },
    {
      label: '注册量',
      key: 'reg_num',
    },
    {
      label: '已支付订单量',
      key: 'done_order_num',
      width: '200',
    },
    {
      label: '订单总金额',
      key: 'order_amount',
      width: '170',
    },
    {
      label: '备注',
      key: 'explain',
      width: '180',
    },
    {
      label: '操作人',
      key: 'creator',
    },
    {
      label: '添加时间',
      key: 'created',
      type: 'date',
    },
    // {
    //   align: 'center',
    //   fixed: 'right',
    //   key: 'op',
    //   width: 160,
    //   label: '操作',
    //   render(record: any) {
    //     return (
    //       <>
    //         <Button
    //           theme='primary'
    //           variant='text'
    //           onClick={() => {
    //             rehandleClickOp(record);
    //           }}
    //         >
    //           修改
    //         </Button>
    //       </>
    //     );
    //   },
    // },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi({...params,...query});
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results || [],
        total: res.total || 0,
      }));
    } catch (err) {
    }
  };

  const fields: FormField[] = [
    { label: '推广平台', name: 'platform', type: 'select', options: CHANNEL_PROMOTION_MAP, required: true },
    { label: '渠道名称', name: 'series', type: 'input', required: true },
    { label: '推广页面', name: 'domain', type: 'input', required: true },
    { label: '备注', name: 'explain', type: 'input' },
    { label: '状态', name: 'status', type: 'radio', options: ENABLE_MAP, required: true },
  ];
  const formFields: any[] = [
    {
      label:'推广平台',
      name:'promotion_platform',
      type:'select',
      options:CHANNEL_PROMOTION_MAP,
      colWrap: {
        colSpan: 2.5,
        labelWidth: 75,
      },
    },
    {
      label:'渠道名称',
      name:'name',
      type:'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 75,
      },
    },
    {
      label:'状态',
      name:'status',
      type:'select',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
      },
      options:ENABLE_MAP
    }
  ];

  useEffect(() => {
    const fetchData = async () => {
      await fetchUserList();
    };
    fetchData();
  }, [query]);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    try {
      if (type == 'Add') {
        await createFormApi(values);
      } else {
      }
    } catch (err) {
      message.success(OPT_ERROR_MSG);
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  const handleAddClick = () => {
    setVisible(true);
  };
  const [sort, setSort] = useState({
    // 按照 status 字段进行排序
    sortBy: 'status',
    // 是否按照降序进行排序
    descending: true,
  });
  const onSortChange = () => {};
  const handleSearch = (values: any) => {
    console.log(values);
    setQuery((pre) => ({
      ...pre,
      ...values,
    }));
  };
  const handleReset = (values:any) => {
    setQuery((pre) => ({
      page:1,
      page_size:10
    })); 
  };
  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            createField={true}
            onAddClick={handleAddClick}
            onSearch={handleSearch}
            onReset={handleReset}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        tableHeight={272}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        sort={sort}
        onSortChange={onSortChange}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: query.page_size,
          total,
          current: query.page,
          showJumper: true,
          onCurrentChange(current, pageInfo) {
            const params = {
              ...query,
              page: pageInfo.current,
            };
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
            fetchUserList(params);
          },
          onPageSizeChange(size) {
            const params = {
              ...query,
              page_size: size,
            };
            fetchUserList(params);
          },
        }}
      />
      <SakuraModal
        visible={visible}
        title={'渠道推广'}
        onClose={() => {
          setVisible(false);
        }}
        onSubmit={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        fields={fields}
      ></SakuraModal>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
